package com.tj.jinzao.presenter;

import android.text.TextUtils;

import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BasePresenter;
import com.tj.jinzao.callback.IUploadView;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.CreateLiveBean;
import com.tj.jinzao.model.ResultResponse;

import java.io.File;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by LiuYX on 2019/4/23.
 */

public class LiveConfigPresenter extends BasePresenter<IUploadView<CreateLiveBean>> {
    public LiveConfigPresenter(IUploadView<CreateLiveBean> view) {
        super(view);
    }
    /**
     * 上传文件
     */
    public void uploadFile(final String localPath) {
        //构建body
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        //文件参数
        if (!TextUtils.isEmpty(localPath)) {
            File file = new File(localPath);
            if (file.isFile()) {
                builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("*/*"), file));
            }
        } else {
            return;
        }
        RequestBody build = builder.build();
        addSubscription(ApiRetrofit.getInstance().getApiService().uploadFile(build), new SubscriberCallBack<String>(mView.getContext()) {
            @Override
            protected boolean isShowProgress() {
                return true;
            }

            @Override
            protected void onSuccess(String response) {
                mView.onUploadSuccess(localPath, response);
            }

            @Override
            protected void onFailure(ResultResponse response) {
                onUploadFailed(localPath, response);
            }
        });
    }

    public void sendLive(HashMap<String,Object> map) {
        long uId = UserManager.getInstance().getUser().getId();
        addSubscription(mApiService.createLive(map), new SubscriberCallBack<CreateLiveBean>(mView.getContext()) {
            @Override
            protected void onSuccess(CreateLiveBean list) {
                if (mView != null) mView.onRequestSuccess(list);
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if(response.getMessage()!=null){
                    if (mView != null)  mView.onRequestError(response.getMessage());
                }else {
                    if (mView != null)  mView.onRequestError(response.getCode());

                }
            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
                if (mView != null) mView.onRequestError(null);
            }
        });
    }


}
